<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

const chartRef = ref()
let chartInstance = null

const initChart = () => {
  if (!chartRef.value) return
  chartInstance = echarts.init(chartRef.value)

  chartInstance.setOption({
    title: {
      text: '活动热度排行',
      left: 'center',
      textStyle: {
        color: '#fff',
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: '{b}：{c}人'
    },
    grid: {
      top: 50,
      left: 80,
      right: 40,
      bottom: 30
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01],
      axisLine: { lineStyle: { color: '#ccc' } },
      axisLabel: { color: '#fff' },
      splitLine: { show: false }
    },
    yAxis: {
      type: 'category',
      data: [],
      axisLine: { lineStyle: { color: '#ccc' } },
      axisLabel: { color: '#fff' }
    },
    series: [
      {
        name: '参与人数',
        type: 'bar',
        data: [],
        barWidth: 20,
        itemStyle: {
          color: '#42b883'
        },
        label: {
          show: true,
          position: 'right',
          color: '#fff'
        }
      }
    ]
  })
}

const updateChart = async () => {
  const res = await axios.get('/api/chart/activity-rank')
  if (res.data.code !== 0) return
  const data = res.data.data

  chartInstance.setOption({
    yAxis: { data: data.map(d => d.name) },
    series: [{ data: data.map(d => d.value) }]
  })
}

onMounted(() => {
  initChart()
  updateChart()
  // const timer = setInterval(updateChart, 8000)
  // onBeforeUnmount(() => clearInterval(timer))
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
